package org.goodsmanager.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.goodsmanager.entity.Cart;
import org.goodsmanager.entity.Product;
import org.goodsmanager.mapper.CartMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车服务类
 *
 * @author Goods Manager System
 * @version 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CartService {

    private final CartMapper cartMapper;
    private final ProductService productService;

    /**
     * 获取用户购物车列表
     */
    public List<Cart> getCartByUserId(String userId) {
        return cartMapper.selectByUserId(userId);
    }

    /**
     * 添加商品到购物车
     */
    @Transactional
    public Cart addToCart(String userId, String productId, Integer quantity) {
        try {
            // 查询商品信息
            Product product = productService.getProductById(productId);
            if (product == null) {
                throw new RuntimeException("商品不存在");
            }

            // 检查商品状态和库存
            if (product.getStatus() != 1) {
                throw new RuntimeException("商品已下架");
            }

            if (product.getStockQuantity() <= 0) {
                throw new RuntimeException("商品库存不足");
            }

            // 检查购物车是否已存在该商品
            Cart existingCartItem = cartMapper.selectByUserIdAndProductId(userId, productId);
            
            if (existingCartItem != null) {
                // 更新数量
                int newQuantity = existingCartItem.getQuantity() + quantity;
                
                // 检查库存是否足够
                if (newQuantity > product.getStockQuantity()) {
                    throw new RuntimeException("库存不足，当前库存: " + product.getStockQuantity());
                }
                
                cartMapper.updateQuantity(userId, productId, newQuantity);
                existingCartItem.setQuantity(newQuantity);
                return existingCartItem;
            } else {
                // 创建新的购物车项
                Cart cartItem = new Cart();
                cartItem.setUserId(userId);
                cartItem.setProductId(productId);
                cartItem.setProductName(product.getProductName());
                cartItem.setProductImage(product.getImageUrl());
                cartItem.setProductPrice(product.getSalePrice().doubleValue());
                cartItem.setQuantity(quantity);
                cartItem.setStockQuantity(product.getStockQuantity());
                cartItem.setProductStatus(product.getStatus());
                cartItem.setSelected(true);
                
                cartMapper.insert(cartItem);
                return cartItem;
            }
        } catch (Exception e) {
            log.error("添加商品到购物车失败", e);
            throw e;
        }
    }

    /**
     * 更新购物车项数量
     */
    @Transactional
    public void updateQuantity(String userId, String productId, Integer quantity) {
        try {
            // 查询购物车项
            Cart cartItem = cartMapper.selectByUserIdAndProductId(userId, productId);
            if (cartItem == null) {
                throw new RuntimeException("购物车项不存在");
            }

            // 检查库存是否足够
            if (quantity > cartItem.getStockQuantity()) {
                throw new RuntimeException("库存不足，当前库存: " + cartItem.getStockQuantity());
            }

            // 更新数量
            cartMapper.updateQuantity(userId, productId, quantity);
        } catch (Exception e) {
            log.error("更新购物车项数量失败", e);
            throw e;
        }
    }

    /**
     * 更新购物车项选中状态
     */
    @Transactional
    public void updateSelected(String userId, String productId, Boolean selected) {
        try {
            cartMapper.updateSelected(userId, productId, selected);
        } catch (Exception e) {
            log.error("更新购物车项选中状态失败", e);
            throw e;
        }
    }

    /**
     * 批量更新购物车项选中状态
     */
    @Transactional
    public void updateSelectedBatch(String userId, List<String> productIds, Boolean selected) {
        try {
            cartMapper.updateSelectedBatch(userId, productIds, selected);
        } catch (Exception e) {
            log.error("批量更新购物车项选中状态失败", e);
            throw e;
        }
    }

    /**
     * 更新用户所有购物车项选中状态
     */
    @Transactional
    public void updateSelectedAll(String userId, Boolean selected) {
        try {
            cartMapper.updateSelectedAll(userId, selected);
        } catch (Exception e) {
            log.error("更新用户所有购物车项选中状态失败", e);
            throw e;
        }
    }

    /**
     * 删除购物车项
     */
    @Transactional
    public void removeFromCart(String userId, String productId) {
        try {
            cartMapper.delete(userId, productId);
        } catch (Exception e) {
            log.error("删除购物车项失败", e);
            throw e;
        }
    }

    /**
     * 批量删除购物车项
     */
    @Transactional
    public void removeFromCartBatch(String userId, List<String> productIds) {
        try {
            cartMapper.deleteBatch(userId, productIds);
        } catch (Exception e) {
            log.error("批量删除购物车项失败", e);
            throw e;
        }
    }

    /**
     * 清空购物车
     */
    @Transactional
    public void clearCart(String userId) {
        try {
            cartMapper.deleteByUserId(userId);
        } catch (Exception e) {
            log.error("清空购物车失败", e);
            throw e;
        }
    }

    /**
     * 获取用户选中的购物车项
     */
    public List<Cart> getSelectedCartItems(String userId) {
        return cartMapper.selectSelectedByUserId(userId);
    }

    /**
     * 获取购物车项数量
     */
    public int getCartItemCount(String userId) {
        return cartMapper.countByUserId(userId);
    }

    /**
     * 计算购物车总金额
     */
    public Double calculateCartTotal(String userId) {
        List<Cart> cartItems = getSelectedCartItems(userId);
        return cartItems.stream()
                .filter(Cart::isValid)
                .mapToDouble(item -> item.getSubtotal().doubleValue())
                .sum();
    }

    /**
     * 获取购物车统计信息
     */
    public Map<String, Object> getCartStatistics(String userId) {
        List<Cart> cartItems = getSelectedCartItems(userId);
        
        int totalItems = cartItems.size();
        BigDecimal totalAmount = BigDecimal.ZERO;
        
        for (Cart item : cartItems) {
            totalAmount = totalAmount.add(BigDecimal.valueOf(item.getSubtotal()));
        }
        
        return Map.of(
            "totalItems", totalItems,
            "totalAmount", totalAmount.doubleValue()
        );
    }

    /**
     * 同步购物车商品信息（当商品信息变更时）
     */
    @Transactional
    public void syncProductInfo(String productId) {
        try {
            Product product = productService.getProductById(productId);
            if (product != null) {
                cartMapper.updateProductInfo(
                        productId,
                        product.getProductName(),
                        product.getImageUrl(),
                        product.getSalePrice().doubleValue(),
                        product.getStockQuantity(),
                        product.getStatus()
                );
            }
        } catch (Exception e) {
            log.error("同步购物车商品信息失败", e);
            throw e;
        }
    }
}